package com.asset.modules.budget.controller;

import com.alibaba.fastjson.JSON;
import com.asset.modules.assets.service.AssetService;
import com.asset.modules.budget.model.Budget;
import com.asset.modules.budget.service.impl.BudgetServiceImpl;
import com.asset.modules.common.model.DownloadBean;
import com.asset.modules.common.model.ResponseBean;
import com.asset.modules.common.model.UglyBean;
import com.asset.modules.common.servcie.ExcelService;
import com.asset.modules.common.utils.Constant;
import com.asset.modules.common.utils.DateUtils;
import com.asset.modules.common.utils.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenchen
 */
@RestController
@CrossOrigin
@RequestMapping("/budget")
@Api(tags = "预算信息接口")
public class BudgetController {
    private static final Logger logger = LoggerFactory.getLogger(BudgetController.class);

    @Autowired
    private BudgetServiceImpl bs;

    @Autowired
    private AssetService as;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private ExcelService excelService;


    private static final String ROOT_ID = "-1";

    private static final String UNAVAILABLE_MSG = "创建预算失败，请先创建上一级预算信息！";

    private static final String UNAVAILABLE_KEY = "关键内容缺失，请重新设置表单信息！";

    private static final String ONLY_ONE_RECORD = "每财年只能有一条预算记录";

    private static final String LIMITED_VALUE   = "预算超过上级总预算";

    private static final String FORMER_BUDGET_INVALID = "上级预算缺失";

    private static final String LACK_FORMER_ID = "上级预算ID缺失，请重新操作";

    private static final String EXIST_CHILDREN_RECORD = "待删除预算存在下级预算，请先删除下级预算";

    private static final String ROOT_TYPE="1";

    private static final String SECOND_TYPE="2";

    private static final String THIRD_TYPE="3";





    /**
     * 保存或更新预算信息
     * @param budget
     * @return
     */
    @ApiOperation(value = "保存或修改预算信息", notes = "公司编码和项目编码必填")
    @RequestMapping(value = "/saveOrModify", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean saveOrModify(@RequestBody Budget budget){
        String formerId = budget.getFormerId();
        String type = budget.getType();
        // 如果类型为空，则直接返回
        String year  = budget.getFiscalYear();
        Object id    =  budget.getId();
        boolean flag;
        List<Budget> b;
        try{
            if(budget.getFormerId()==null){
                return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), LACK_FORMER_ID, null);
            }
            //判断是否是新增信息
            if(id==null){
                QueryWrapper<Budget> qw = new QueryWrapper<>();
                qw.eq("fiscal_year", year);

                switch (type){
                    case ROOT_TYPE:
                        qw.eq("company_id", "-1");
                        b = bs.list(qw);
                        if(b.size()>0) {
                            //当年有预算信息
                            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), ONLY_ONE_RECORD, null);
                        }
                        break;
                    case SECOND_TYPE:
                        qw.eq("company_id", "-1");
                        b = bs.list(qw);
                        if(b.size()==0){
                            //上一级预算信息不存在
                            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), UNAVAILABLE_MSG, null);
                        } else {
                            QueryWrapper<Budget> _qw = new QueryWrapper<>();

                            _qw.eq("company_id", budget.getCompanyId());
                            _qw.eq("fiscal_year", budget.getFiscalYear());
                            _qw.eq("type", SECOND_TYPE);
                            b = bs.list(_qw);
                            //判断是否当年已经有预算信息
                            if(b.size()>0){
                                return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), ONLY_ONE_RECORD, null);
                            }

                        }
                        break;
                    case THIRD_TYPE:
                        qw.eq("company_id", budget.getFormerId());
                        b = bs.list(qw);
                        if(b.size()==0){
                            //上一级预算信息不存在
                            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), UNAVAILABLE_MSG, null);
                        }else {
                            QueryWrapper<Budget> _qw = new QueryWrapper<>();
                            _qw.eq("project_id", budget.getProjectId());
                            _qw.eq("company_id", budget.getCompanyId());
                            b = bs.list(_qw);
                            if(b.size()>0){
                                return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), ONLY_ONE_RECORD, null);
                            }
                        }
                        break;
                    default:
                        break;
                }

            }

            //针对不同的节点预算做处理
            if(type==null){
                return new ResponseBean(HttpStatus.OK.value(), UNAVAILABLE_KEY, budget.getType());
            }else if(type.equals(THIRD_TYPE)){
                double projectBudget = budget.getProjectBudget();
                Budget formerBudget  = bs.getBudgetByCompanyId(formerId).get(0);
                String companyBudget = formerBudget.getCompanyBudget();
                if(companyBudget==null){
                    return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), FORMER_BUDGET_INVALID, null);
                }
                flag = bs.verifyLimitedBudget(Double.valueOf(companyBudget), projectBudget, formerId, id, year, type);
                if(flag){
                    return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), LIMITED_VALUE, null);
                }
                //判断如果为三级节点，则计算花费与余额
                budget = bs.expenditureAndBalance(budget);
            }else if (type.equals(SECOND_TYPE)){

                String companyBudget = budget.getCompanyBudget();
                Budget formerBudget  = (bs.getBudgetByCompanyId(formerId)).get(0);
                if(formerBudget==null){
                    return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), FORMER_BUDGET_INVALID, null);
                }
                String totalBudget = formerBudget.getCompanyBudget();
                flag = bs.verifyLimitedBudget(Double.valueOf(totalBudget), Double.valueOf(companyBudget),formerId, id, year, type);
                if(totalBudget!=null&&companyBudget!=null){
                    if(flag){
                        return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), LIMITED_VALUE, null);
                    }
                }
            }
            flag = bs.saveOrUpdate(budget);
            return new ResponseBean(HttpStatus.OK.value(), Constant.SUCCESS_OPERATION, flag);
        }catch (Exception e){
            logger.error("错误日志为:{}",e.getMessage());
           return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), Constant.FAILED_OPERATION, false);
        }

    }

    /**
     * 根据Id获取预算信息
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID获取预算信息")
    @RequestMapping(value = "/byId", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean getBudgetById(@RequestParam String id){
        String msg = "获取预算信息";
        if(StringUtil.isBlank(id)){
            msg  = "查询序号为空";
        }
        Budget budget = bs.getBudgetById(Long.valueOf(id));
        budget = bs.expenditureAndBalance(budget);
        return new ResponseBean(HttpStatus.OK.value(), msg, budget);
    }

    /**
     * 获取预算分页信息
     * @param uglyBean
     * @return
     */
    @ApiOperation(value = "预算分页数据", notes = "page对象，设置current(当前页), size(每页显示条数))")
    @RequestMapping(value = "/getPages", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean getBudgetPages(@RequestBody UglyBean uglyBean){
        Page page = JSON.parseObject(uglyBean.getPage(), Page.class);
        Budget budget = JSON.parseObject(uglyBean.getAnything(), Budget.class);
        IPage<Budget> budgets = bs.getBudgetPage(page, budget);
        return new ResponseBean(HttpStatus.OK.value(), "获取预算分页信息成功", budgets);
    }

    /**
     * 删除预算信息
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除[批量]预算信息", notes = "根据ID列表删除预算信息")
    @RequestMapping(value = "/remove", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean removeBudgetById(@RequestParam String ids){
        QueryWrapper<Budget> qw = new QueryWrapper<>();
        String msg = "删除预算信息";
        if(StringUtil.isBlank(ids)){
            msg  = "待删除预算ID为空";
        }
        String[] removeIds = ids.split(",");
        List list = new ArrayList();
        List tempList;
        for(String id : removeIds){
            Budget b = bs.getBudgetById(Long.valueOf(id));
            //查询如果不为三级预算，则要查看关联数据情况
            if(!b.getType().equals(THIRD_TYPE)){
                String companyId = b.getCompanyId();
                qw.eq("former_id", companyId);
                tempList = bs.list(qw);
                if(tempList.size()>0){
                    return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), EXIST_CHILDREN_RECORD, null);
                }
            }
            list.add(id);
        }
        return new ResponseBean(HttpStatus.OK.value(), msg, bs.removeByIds(list));
    }


    @ApiOperation(value = "Excel文件下载")
    @RequestMapping(value = "/download", method = RequestMethod.POST)
    @ResponseBody
    public void downloadBugetExcel(@RequestBody DownloadBean bean){
        long size = bean.getSize();
        Budget a   =   JSON.parseObject(bean.getAnything(), Budget.class);
        String fileName;
        String sheetName;
        String timestamp = DateUtils.getDateTimeNowStr();
        ResponseBean rb  = new ResponseBean();
        int startPage = bean.getStartPage();
        int endPage   = bean.getEndPage();
        fileName = bean.getFileName().isEmpty() ? "temp"+timestamp :  bean.getFileName();
        sheetName = bean.getSheetName().isEmpty() ? "temp"+timestamp :  bean.getSheetName();
        response.setContentType("mutipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xls");
        if(bean.getData().size()!=0){
            excelService.writeExcel(response, Budget.class, sheetName, bean.getData());
        }else if(startPage>endPage){
            rb.setMsg("error, 开始页不能大于结束页");
        }else {
            excelService.writeExcel(response,  a,  sheetName, startPage, endPage, size);
            rb.setMsg("下载成功！");
        }
    }



}
